package com.ly.wxPay.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ly.common.core.bean.R;
import com.ly.common.core.bean.dto.CommonBatchUpdateDTO;
import com.ly.wxPay.bean.dto.WxOrderDTO;
import com.ly.wxPay.bean.entity.WxOrder;
import com.ly.wxPay.enums.OrderStatus;
import com.ly.wxPay.enums.WxRefundStatus;
import com.ly.wxPay.mapper.WxOrderMapper;
import com.ly.wxPay.service.IWxOrderService;
import com.ly.wxPay.util.OrderNoUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.List;

/**
 * 支付-订单表-impl
 *
 * @author luoyun
 * @Date: 2025-11-22
 */
@Service
public class WxOrderServiceImpl extends ServiceImpl<WxOrderMapper, WxOrder> implements IWxOrderService {

    @Override
    public R getId(String id) {
        WxOrder entity = this.getById(id);
        if (entity == null) {
            return R.fail("未找到对应数据");
        }
        return R.ok(entity);
    }

    @Override
    public R getList(WxOrder entity) {
        List<WxOrder> list = this.list(
                new LambdaQueryWrapper<WxOrder>()
                        .orderByDesc(WxOrder::getCreateTime)
        );
        return R.ok(list);
    }

    @Override
    public R getPage(WxOrder entity, Page<WxOrder> page) {
        IPage<WxOrder> pageList = this.page(
                page,
                new LambdaQueryWrapper<WxOrder>()
                        .like(StrUtil.isNotEmpty(entity.getOrderNo()), WxOrder::getOrderNo, entity.getOrderNo())
                        .eq(StrUtil.isNotEmpty(entity.getOrderStatus()), WxOrder::getOrderStatus, entity.getOrderStatus())
                        .orderByDesc(WxOrder::getCreateTime)
        );
        return R.ok(pageList);
    }

    @Override
    public R add(WxOrder entity) {
        boolean flag = this.save(entity);
        return flag ? R.ok(true, "创建成功") : R.fail("创建失败");
    }

    @Override
    public R edit(WxOrder entity) {
        boolean flag = this.updateById(entity);
        return flag ? R.ok(true, "修改成功") : R.fail("修改失败");
    }

    @Override
    public R delete(String id) {
        boolean flag = this.removeById(id);
        return flag ? R.ok(true, "删除成功") : R.fail("删除失败");
    }

    @Override
    public R deleteBatch(String ids) {
        boolean flag = this.removeByIds(Arrays.asList(ids.split(",")));
        return flag ? R.ok(true, "批量删除成功") : R.fail("批量删除失败");
    }

    @Override
    public R updateBatch(CommonBatchUpdateDTO<WxOrder> dto) {
        List<WxOrder> datas = dto.getDatas();
        boolean flag = this.saveOrUpdateBatch(datas);
        return flag ? R.ok(true, "批量修改成功") : R.fail("批量修改失败");
    }

    @Override
    public String getOrderStatus(String orderNo) {
        WxOrder one = this.getOne(
                new LambdaQueryWrapper<WxOrder>()
                        .eq(WxOrder::getOrderNo, orderNo)
        );
        if (one == null) {
            return null;
        }
        return one.getOrderStatus();
    }

    @Override
    public WxOrder addOrder(WxOrderDTO dto) {
        // 避免重复创建未支付的订单
        List<WxOrder> list = this.list(
                new LambdaQueryWrapper<WxOrder>()
                        .eq(WxOrder::getProductId, dto.getProductId())
                        .eq(WxOrder::getOrderStatus, OrderStatus.NOTPAY.getType())
        );
        if (CollUtil.isNotEmpty(list)) {
            return list.get(0);
        }
        // 无数据则生成订单
        WxOrder wxOrder = BeanUtil.copyProperties(dto, WxOrder.class);
        wxOrder.setTotalFee(dto.getAmount().multiply(new BigDecimal("100")).intValue());
        wxOrder.setOrderStatus(OrderStatus.NOTPAY.getType());
        wxOrder.setOrderNo(OrderNoUtils.getOrderNo());
        this.save(wxOrder);
        return wxOrder;
    }

    /**
     * 根据订单号更新订单状态
     *
     * @param orderNo
     * @param orderStatus
     */
    @Override
    public R updateStatusByOrderNo(String orderNo, OrderStatus orderStatus) {
        boolean flag = this.update(
                new LambdaUpdateWrapper<WxOrder>()
                        .eq(WxOrder::getOrderNo, orderNo)
                        .set(WxOrder::getOrderStatus, OrderStatus.SUCCESS.getValue())
        );
        return flag ? R.ok(true, "操作订单成功") : R.fail("操作订单失败");
    }

    @Override
    public List<WxOrder> getNoPayOrderByDuration(int minutes) {
        Instant instant = Instant.now().minus(Duration.ofMinutes(minutes));
        return this.list(
                new LambdaQueryWrapper<WxOrder>()
                        .eq(WxOrder::getOrderStatus, WxRefundStatus.PROCESSING.getType())
                        .le(WxOrder::getCreateTime, instant)
        );
    }
}
